package com.nami.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nami.common.domain.pojo.SysMenu;
import com.nami.common.domain.pojo.SysRole;
import com.nami.system.mapper.SysMenuMapper;
import com.nami.system.service.ISysMenuService;
import com.nami.system.service.ISysRoleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    private final ISysRoleService sysRoleService;

    @Override
    public List<SysMenu> getMenuByRoleIds(List<Long> roleIds) {
        return baseMapper.getMenuByRoleIds(roleIds);
    }

    @Override
    public List<SysMenu> getTreeMenuByUserId(Long userId) {
        List<SysRole> roles = sysRoleService.getRolesByUserId(userId);
        List<Long> roleIds = roles.stream().map(SysRole::getId).collect(Collectors.toList());
        List<SysMenu> menus = this.getMenuByRoleIds(roleIds);
        // 获取用户的菜单信息, 是一个树形菜单结构
        return getTreeMenus(menus);
    }

    /**
     * 根据菜单集合获取树形结构
     *
     * @param menus 菜单集合
     * @return 菜单的树形结构
     */
    private List<SysMenu> getTreeMenus(List<SysMenu> menus) {
        if (CollectionUtil.isEmpty(menus)) {
            return null;
        }
        return menus.stream().filter(menu -> menu.getParentId() == 0).peek((menu) -> menu.setChildren(getChildren(menu, menus))).collect(Collectors.toList());
    }

    /**
     * 递归获取子菜单
     *
     * @param menu  菜单列表
     * @param menus 最上级菜单
     * @return 菜单树
     */
    private List<SysMenu> getChildren(SysMenu menu, List<SysMenu> menus) {
        return menus.stream().filter(
                item -> item.getParentId().equals(menu.getId())
        ).peek(item -> item.setChildren(getChildren(item, menus))).collect(Collectors.toList());
    }
}
